package user

import (
	"github.com/gin-gonic/gin"
	"apiserver/errno"
	"github.com/lexkong/log"
	"apiserver/handler"
	"apiserver/model"
)

//创建用户
func Create(c *gin.Context) {
	log.Infof("创建用户")
	var r CreateRequest
	if err := c.Bind(&r); err != nil {
		handler.SendResponse(c, errno.ErrBind, nil)
		return
	}
	if err := r.ValidateCreate(); err != nil {
		handler.SendResponse(c, err, nil)
		return
	}

	u := model.UserModel{
		Username: r.Username,
		Password: r.Password,
		Email:    r.Email,
	}
	if err := u.Validate(); err != nil {
		handler.SendResponse(c, errno.ErrValidation, nil)
		return
	}

	if err := u.Encrypt(); err != nil {
		handler.SendResponse(c, errno.ErrEncrypt, nil)
		return
	}
	//验证输入的密码是否一致
	vPassword := r.VPassword
	if err := u.Compare(vPassword); err != nil {
		handler.SendResponse(c, errno.ErrUserPasswordNotMatch, nil)
		return
	}
	if err := u.Create(); err != nil {
		handler.SendResponse(c, errno.ErrDatabase, nil)
		return
	}
	//创建成功后显示用户信息
	rsp := CreateResponse{
		Username: r.Username,
	}
	handler.SendResponse(c, nil, rsp)
}
